<?php
namespace control;
/*
*客户类
*/

use JetBrains\PhpStorm\NoReturn;

class clientPriceListClass extends adIndexClass
{
	private const title            = '客户价格本';
	private const page             = 'clientPriceList';
	private const table            = 'store_client_price';
	private const tableKehu        = 'kehu';
	private const tableMaterial    = 'material';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'clientPriceSearch':
                $tr = [
                    'code'  => [
                        'name'  => "产品编码",
                        'width' => 150,
                    ],
                    'name'  => [
                        'name'  => '产品名称',
                        'width' => 120,
                    ],
                    'materialAliasNo'  => [
                        'name'  => '客户料号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialAlias'         => [
                        'name'  => '客户品名',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 80,
                    ],
                    'price'          => [
                        'name'  => 'BOM材料成本价('. static::$unit . ')',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'salePrice'          => [
                        'name'  => '销售基准价('. static::$unit . ')',
                        'width' => 150,
                    ],
                    'agreedPrice'          => [
                        'name'  => '协议价（'. static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'agreedDiscount'          => [
                        'name'  => '协议折扣（%）',
                        'width' => 150,
                    ],
                    'dealPrice'          => [
                        'name'  => '成交价（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'updateTime'          => [
                        'name'  => '更新时间',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "客户编码",
                        'width' => 100,
                    ],
                    'companyName' => [
                        'name'  => "客户名称",
                        'width' => 150,
                    ],
                    'code'  => [
                        'name'  => "产品编码",
                        'width' => 150,
                    ],
                    'name'  => [
                        'name'  => '产品名称',
                        'width' => 120,
                    ],
                    'materialAliasNo'  => [
                        'name'  => '客户料号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialAlias'         => [
                        'name'  => '客户品名',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 80,
                    ],
                    'price'          => [
                        'name'  => 'BOM材料成本价('. static::$unit . ')',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'salePrice'          => [
                        'name'  => '销售基准价('. static::$unit . ')',
                        'width' => 150,
                    ],
                    'agreedPrice'          => [
                        'name'  => '协议价（'. static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'agreedDiscount'          => [
                        'name'  => '协议折扣（%）',
                        'width' => 150,
                    ],
                    'dealPrice'          => [
                        'name'  => '成交价（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'updateTime'          => [
                        'name'  => '更新时间',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function materialClientPriceOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码"   => text(array("name" => "orderNo")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "客户名称"   => text(array("name" => "companyName")),
                    '产品编码'  => text(array("name" => "materialCode")),
                ],
                [
                    '产品名称'  => text(array("name" => "materialName")),
                    '规格型号'  => text(array("name" => "model")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 物料页卡客户价格本
     *
     * @return bool|string
     */
    public function materialClientPrice(): bool|string
    {
        $html = $this->materialClientPriceOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function materialClientPriceSearch(): bool|string
    {
        $khid = $this->post('targetId');
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'coid' => self::$coid,
            'khid' => $khid,
        ];
        // 客户搜索
        if ($this->post('orderNo') || $this->post('companyName')) {
            $kWhere = search([
                "="    => $equal,
                "like" => [
                    'orderNo'     => $this->post('orderNo'),
                    'companyName' => $this->post('companyName'),
                ],
            ]);
            $where  .= " AND `khid` IN (SELECT khid FROM `kehu` WHERE 1=1 $kWhere)  ";
        }
        // 物料搜索
        if ($this->post('materialCode') || $this->post('materialName') || $this->post('model')) {
            $mWhere = search([
                "="    => $equal,
                "like" => [
                    'code'  => $this->post('materialCode'),
                    'name'  => $this->post('materialName'),
                    'model' => $this->post('model'),
                ],
            ]);
            $where  .= " AND `materialId` IN (SELECT id FROM `material` WHERE 1=1 $mWhere)  ";
        }
        //生成查询语句
        $where                       .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $kehu     = query(self::tableKehu, " khid = '$array[khid]' ");
            $material = query(self::tableMaterial, " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'orderNo':
                    case 'companyName':
                        $row[] = $kehu[$key];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case 'salePrice':
                        $row[] = self::lostZero($material['salePrice'],'pricePrecision');
                        break;
                    case 'agreedPrice':
                        $row[] = self::lostZero($array['agreedPrice'],'pricePrecision');
                        break;
                    case 'agreedDiscount':
                        $row[] = ($array['agreedDiscount'] > 0 ? ($array['agreedDiscount'] * 100) . '%' : 0);
                        break;
                    case 'dealPrice':
                        $row[] = self::lostZero($array['dealPrice'],'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='priceForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function clientPriceOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '产品编码'  => text(array("name" => "materialCode")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    '产品名称'  => text(array("name" => "materialName")),
                    '规格型号'  => text(array("name" => "model")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 客户页卡价格本
	 *
	 * @return bool|string
	 */
	public function clientPrice(): bool|string
	{
        $html = $this->clientPriceOptions(false);
        $button = "";
		//返回
		$json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
		return json_encode($json, 320);
	}

	public function clientPriceSearch(): bool|string
	{
		$khid = $this->post('targetId');
		//查询结果
		$where = ' 1=1 ';
		$equal = [
			'coid' => self::$coid,
			'khid' => $khid,
		];
		// 物料搜索
		if ($this->post('materialCode') || $this->post('materialName') || $this->post('model')) {
			$mWhere = search([
				"="    => $equal,
				"like" => [
					'code'  => $this->post('materialCode'),
					'name'  => $this->post('materialName'),
					'model' => $this->post('model'),
				],
			]);
			$where  .= " AND `materialId` IN (SELECT id FROM `material` WHERE 1=1 $mWhere)  ";
		}
		//生成查询语句
		$where .= search([
			"=" => $equal,
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page  = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("priceForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box" => array("name" => "listId", "value" => $array['khid']),
			);
			$material = query(self::tableMaterial, " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case 'salePrice':
                        $row[] = self::lostZero($material['salePrice'],'pricePrecision');
                        break;
                    case 'agreedPrice':
                        $row[] = self::lostZero($array['agreedPrice'],'pricePrecision');
                        break;
                    case 'agreedDiscount':
                        $row[] = ($array['agreedDiscount'] > 0 ? ($array['agreedDiscount'] * 100) . '%' : 0);
                        break;
                    case 'dealPrice':
                        $row[] = self::lostZero($array['dealPrice'],'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='priceForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码"   => text(array("name" => "orderNo")),
                    "客户名称"   => text(array("name" => "companyName")),
                    '产品编码'  => text(array("name" => "materialCode")),
                ],
                [
                    '产品名称'  => text(array("name" => "materialName")),
                    '规格型号'  => text(array("name" => "model")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*客户列表-查询条件*/
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch(): bool|string
	{
		//查询结果
		$where = ' 1=1 ';
		$equal = [
			'coid' => self::$coid,
		];
		// 客户搜索
		if ($this->post('orderNo') || $this->post('companyName')) {
			$kWhere = search([
				"="    => $equal,
				"like" => [
					'orderNo'     => $this->post('orderNo'),
					'companyName' => $this->post('companyName'),
				],
			]);
			$where  .= " AND `khid` IN (SELECT khid FROM `kehu` WHERE 1=1 $kWhere)  ";
		}
		// 物料搜索
		if ($this->post('materialCode') || $this->post('materialName') || $this->post('model')) {
			$mWhere = search([
				"="    => $equal,
				"like" => [
					'code'  => $this->post('materialCode'),
					'name'  => $this->post('materialName'),
					'model' => $this->post('model'),
				],
			]);
			$where  .= " AND `materialId` IN (SELECT id FROM `material` WHERE 1=1 $mWhere)  ";
		}
		//生成查询语句
		$where                       .= search([
			"=" => $equal,
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"  => array("name" => "listId", "value" => $array['id']),
				"edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
			);
			$kehu     = query(self::tableKehu, " khid = '$array[khid]' ");
			$material = query(self::tableMaterial, " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'orderNo':
                    case 'companyName':
                        $row[] = $kehu[$key];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case 'salePrice':
                        $row[] = self::lostZero($material['salePrice'],'pricePrecision');
                        break;
                    case 'agreedPrice':
                        $row[] = self::lostZero($array['agreedPrice'],'pricePrecision');
                        break;
                    case 'agreedDiscount':
                        $row[] = ($array['agreedDiscount'] > 0 ? ($array['agreedDiscount'] * 100) . '%' : 0);
                        break;
                    case 'dealPrice':
                        $row[] = self::lostZero($array['dealPrice'],'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js() . clear;
		return json_encode($json, 320);
	}

	public function js()
	{
		return <<<eof
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
       $('#clientPriceListAddMx').hide()
       $("#materialName").html(res.data.name);
       $("#salesPrice").html(res.data.salePrice);
       $("[name='materialId']").val(res.data.materialId);
    },'json');
}
function countPrice(e){
    let agreedPrice = Number($("[name='agreedPrice']").val());
    let agreedDiscount = Number($("[name='agreedDiscount']").val())/100;
    $("#dealPrice").html((agreedPrice*agreedDiscount).toFixed(2))
}
</script>
eof;
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$info = query(self::table, " id = '" . $this->post('id') . "' ");
		$material = query('material',"id = '$info[materialId]'");
		$name = materialClass::getName($info['materialId']);
		$html = $this->layerEdit(array(
			"table" => array(
				array(
					must . "物料：" => "<span id='materialName' class='exceed-ellipsis' style='max-width: 90%;'>$name</span>&nbsp;<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addMx',{})\">选择</span>" . hidden(array('name' => 'materialId', 'value' => $info['materialId'])),
				),
				array(
                    must . "客户：" => clientProfileClass::kehuSelect(array('value' => $info['khid'])),
					"客户料号：" => text(array('name' => 'materialAliasNo', 'value' => $info['materialAliasNo'])),

				),
				array(
                    "客户品名：" => text(array('name' => 'materialAlias', 'value' => $info['materialAlias'])),
					"BOM材料成本价：" => text(array('name' => 'price', 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($info['price'],'pricePrecision'))),
				),
				array(
                    "销售基准价：" =>"<span id='salesPrice'>".self::lostZero($material['salePrice'],'pricePrecision')."</span>",
					"协议价：" => text(array('name' => 'agreedPrice','blur'=>'countPrice', 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($info['agreedPrice'],'pricePrecision'))),
				),
                array(
                    "协议折扣：" => text(array('name' => 'agreedDiscount', 'blur'=>'countPrice','type' => 'number', 'unit' => '%', 'value' => (float)$info['agreedDiscount'] * 100)),
                    "成交价："=>"<span id='dealPrice'>".self::lostZero($info['dealPrice'],'pricePrecision')."</span>"
                )
			),
		));
		return $this->layer(array("title" => "编辑", "height" => 350, "width" => 900, "html" => $html));
	}


	public function editEdit()
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			"khid"            => $this->post('khid'),
			"materialId"   => $this->post('materialId'),
			"materialAliasNo" => $this->post('materialAliasNo'),
			"materialAlias"   => $this->post('materialAlias'),
			"price"           => $this->post('price')?self::formattingFigure($this->post('price'),'pricePrecision'):0,
			"agreedPrice"     => $this->post('agreedPrice')?self::formattingFigure($this->post('agreedPrice'),'pricePrecision'):0,
			"agreedDiscount"  => (float)$this->post('agreedDiscount') / 100,
		];
		$field['dealPrice'] = self::formattingFigure($field['agreedPrice']*$field['agreedDiscount'],'pricePrecision');
		$annotation = [
			'khid'          => '客户',
			'materialId' => '物料',
		];
		$rules      = [
			'khid'          => 'required',
			'materialId' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::total(array(
		    'table' => self::table,
            'where' => "materialId = '$field[materialId]' and khid = '$field[khid]' and coid = '" . self::$coid . "'  and id !='$id'"
            )) > 0) {
			$json['warn'] = '此客户已存在此物料的价格本';
		} else {
			if (!$info['id']) {
				$field        = array_merge($field, [
					'id'   => $id,
					'coid' => self::$coid,
					'stid' => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"where" => $where,
					"field" => $field,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
			}
		}

		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $word = $power = '';
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				//最后删除基本参数
				delete(array("table" => self::table, "where" => " id = '$id' "));
				//返回
				$warn = "删除成功";
				$x++;
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }  else {
            $exampleData[] = ['测试企业','88','钢板','低合金结构钢钢板','GB3274-88','kg',1,
                1,80,0.8,'(样例数据，导入时请删除本条数据)'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '客户名称'=>$example[0],
                            '客户料号'=>$example[1],
                            '客户品名'=>$example[2],
                            '产品名称'=>$example[3],
                            '规格型号'=>$example[4],
                            '单位'=>$example[5],
                            'BOM材料成本价'=>$example[6],
                            '协议价'=>$example[7],
                            '协议折扣'=>$example[8],
                            '备注'=>$example[9],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了客户导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
	/*数据导入*/
	public function importData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power(self::page, 'import')) {
			$json['warn'] = '你还没有导入的权限';
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
					$kehu     = query("kehu", "companyName = '$cell[客户名称]' and coid = '" . self::$coid . "' ");
					$material = query('material', "coid = '" . self::$coid . "' and name = '$cell[产品名称]' and model = '$cell[规格型号]' and state = '启用'");
					$field      = [
						'id'              => suiji(),
						'coid'            => self::$coid,
						'stid'            => self::$stid,
						"khid"            => $kehu['khid'],
						"materialId"      => $material['id'],
						"materialAliasNo" => $cell['客户料号'],
						"materialAlias"   => $cell['客户品名'],
						"unit"            => $cell['单位']?:$material['unit'],
						"price"           => $cell['BOM材料成本价']?self::formattingFigure($cell['BOM材料成本价'],'pricePrecision'):0,
						"agreedPrice"     => $cell['协议价']?self::formattingFigure($cell['协议价'],'pricePrecision'):0,
						"agreedDiscount"  => (float)$cell['协议折扣'] / 100,
						'text'            => $cell['备注'],
					];
					$annotation = [
						'khid'          => '客户',
						'materialId' => '物料',
					];
					$rules      = [
						'khid'          => 'required',
						'materialId' => 'required',
					];
					// 校验是否符合规则
					$vt     = new \verify();
					$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
					if ($result === false) {
						$text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
					} elseif(!in_array($field['unit'],machiningOrderClass::unitOption($field['materialId']))){
                        $text .="\n第【{$row_list}】行此单位不在物料单位内";
                    }elseif (static::total(array('table' => self::table, 'where' => "materialId = '$field[materialId]' and khid = '$field[khid]' and coid = '" . self::$coid . "'")) > 0) {
                        $text .= "\n第【{$row_list}】行此客户已存在此物料的价格本";
					} else {
                        $field['dealPrice'] = self::formattingFigure($field['agreedPrice']*$field['agreedDiscount'],'pricePrecision');
						$warn = insert(["table" => self::table, "field" => $field]);
						if (in_array($warn, ["新增成功", "更新成功"])) {
							$x++;
							$text .= "第【{$row_list}】行导入成功<br>";
						} else {
							$text .= "第【{$row_list}】行导入失败：编辑失败<br>";
						}
					}
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
			$this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}

	/**
	 * @return bool|string
	 */
	public function addMx()
	{
		$html   =
            materialClass::typeSelect(name: 'type').
			text(array("name" => "code", "title" => "产品编码")) .
			text(array("name" => "materialName", "title" => "产品名称")) .
			text(array("name" => "model", "title" => "规格型号"));
		$button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button));
	}

	/**
	 *添加产品
	 */
	public function addMxSearch()
	{
		$like        = [
			'a.name'          => $this->post('materialName'),
			'code'            => $this->post('code'),
			'model'           => $this->post('model'),
			'a.supplyControl' => '允许销售',
			'a.typePath' => $this->post('type'),
		];
		$equal       = [
			'a.coid'   => self::$coid,
			'a.state'  => '启用',
		];
		$where       = search(["like" => $like, "=" => $equal]);
		$page        = $this->page([
			"table"   => "material as a",
			"field"   => "a.*",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => "a.`time` ASC",
		]);
		$materialObj = new materialClass();
		//获取表头
		$tr[]     = ['', '分类', '产品编码', '产品名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$checkBox = "<input name='mxId' value='$array[id]' type='radio'>";
			$tr[]     = array(
				$checkBox,
				$materialObj::getTypePath($array['typeId']),
				$array['code'],
				$array['name'],
				$array['model']
			);
		}
		$json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$mxId = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxId)) {
			$json['warn'] = '请选择产品';
		} else {
            $material = query('material',"id = '$mxId'");
			$json['data'] = [
				'materialId' => $material['id'],
				'name'          => materialClass::getName($material['id']),
                'salePrice'=> self::lostZero($material['salePrice'],'pricePrecision')
			];
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}

	/**
	 * 导出
	 */
	 public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $kehu     = query(self::tableKehu, " khid = '$array[khid]' ");
                $material = query(self::tableMaterial, " id = '$array[materialId]' ");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户编码'=>$kehu['orderNo'],
                            '客户名称'=>$kehu['companyName'],
                            '产品编码'=>$material['code'],
                            '产品名称'=>$material['name'],
                            '客户料号'=>$array['materialAliasNo'],
                            '客户品名'=>$array['materialAlias'],
                            '规格型号'=>$material['model'],
                            '单位'=> $material['unit'],
                            'BOM材料成本价'=> self::lostZero($array['price'],'pricePrecision'),
                            '销售基准价'=> self::lostZero($material['salePrice'],'pricePrecision'),
                            '协议价'=>self::lostZero($array['agreedPrice'],'pricePrecision'),
                            '协议折扣%'=> ($array['agreedDiscount'] > 0 ? ($array['agreedDiscount'] * 100) . '%' : 0),
                            '成交价元'=>self::lostZero($array['dealPrice'],'pricePrecision'),
                            '更新时间'=>$array['updateTime'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = $this->control['name'] . "导出了客户价格本";
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, "客户价格本.xlsx");
            exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));

	}
    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'客户料号',
                    'aliasName'=>'客户料号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户品名',
                    'aliasName'=>'客户品名',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'BOM材料成本价',
                    'aliasName'=>'BOM材料成本价',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协议价',
                    'aliasName'=>'协议价',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'协议折扣',
                    'aliasName'=>'协议折扣%',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],

            ]
        };
    }


    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'客户料号',
                    'aliasName'=>'客户料号',
                ],
                [
                    'columnName'=>'客户品名',
                    'aliasName'=>'客户品名',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'BOM材料成本价',
                    'aliasName'=>'BOM材料成本价（元）',
                ],
                [
                    'columnName'=>'销售基准价',
                    'aliasName'=>'销售基准价（元）',
                ],
                [
                    'columnName'=>'协议价',
                    'aliasName'=>'协议价（元）',
                ],
                [
                    'columnName'=>'协议折扣%',
                    'aliasName'=>'协议折扣（%）',
                ],
                [
                    'columnName'=>'成交价',
                    'aliasName'=>'成交价（元）',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
            ]
        };
    }
}
